package com.zhi.mbtibot.controller;

import com.zhi.mbtibot.common.Result;
import com.zhi.mbtibot.entity.User;
import com.zhi.mbtibot.service.UserService;
import com.zhi.mbtibot.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 功能: 用户控制器
 * 作者:YukiSu
 * 日期:2024/7/21 1:03
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    TokenUtil tokenUtil;

    @GetMapping()
    public Result getUserList() {
        return Result.success(userService.getAllUser());
    }

    //创建用户
    @PostMapping("/register")
    public Result createUser(@RequestBody User user) {
        if (userService.getUserByUserName(user.getUsername()) != null) {
            return Result.error("用户名已存在");
        }
        if (user.getUsername().isBlank()) {
            return Result.error("用户名不能为空");
        }
        if (user.getPassword().isBlank()) {
            user.setPassword(user.getUsername());
        }
        userService.addUser(user);
        return Result.success("创建用户成功");
    }
    // 登录验证,获取token
    @GetMapping("/login")
    public Result getToken(@RequestParam String username, @RequestParam String password) {
        if (username.isBlank() || password.isBlank()) {
            return Result.error("用户名或密码不能为空");
        }
        if (userService.getUserByUserName(username) == null) {
            return Result.error("用户名不存在");
        }
        if (userService.getUserByUserName(username).getPassword().equals(password)) {
            return Result.success(tokenUtil.getToken(username, password));
        }
        return Result.error("用户名或密码错误");
    }

    //以下是根据uid进行操作
    @PutMapping("/{uid}")
    public Result updateUserByUid(@PathVariable("uid") Integer uid, @RequestBody User user) {
        if (userService.getUserById(uid) == null) {
            return Result.error("用户ID不存在");
        }
        user.setUid(uid);
        userService.updateUser(user);
        return Result.success("更新用户成功");
    }
    @DeleteMapping("/{uid}")
    public Result deleteUserByUid(@PathVariable("uid") Integer uid) {
        if (userService.getUserById(uid) == null) {
            return Result.error("用户ID不存在");
        }
        userService.deleteUser(uid);
        return Result.success("删除用户成功");
    }
    @GetMapping("/{uid}")
    public Result getUserByUid(@PathVariable("uid") Integer uid) {
        if (userService.getUserById(uid) == null) {
            return Result.error("用户不存在");
        }
        return Result.success(userService.getUserById(uid));
    }

}